import axios from 'axios'
import appConfig from '@/config'
import * as actions from "@/store/actions";

//  响应拦截器
axios.interceptors.response.use(response => {
    let res = response.data

    return res
}, error => {
    return Promise.reject(error)
})


export const request = ({url, type = 'get', params}) => {
    return new Promise((resolve, reject) => {
        type = type.toLowerCase()

        let config = {
            method: type,
            url: appConfig.api_baseurl + url,
            withCredentials: true
        }

        if (params !== undefined) {
            if (type === 'get') {
                config.params = params
            } else {
                config.data = params
            }
        }

        axios(config).then(res => {
            if (res.code === 1) {
                resolve(res.data || {})
                return
            }

            //  未登录拦截
            if (res.code === 3) {
                window.localforage.removeItem('userInfo')
                actions.updateAppSetting({
                    user: null,
                    isLogin: false
                })

                window.location.hash = '#/login'
            }

            reject({msg: res.data || '操作失败！'})
        }).catch(err => {
            console.log('api catch err :::::' + err)
            reject({msg: '请求失败！'})
        })
    })
}